package com.xsd.parser.util;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class FileUtil {

    /**
     * 保存文件到路径
     * @param schema
     * @param path
     * @throws IOException
     */
    public static void saveTo(String schema,String path) throws IOException {
        String local = System.getProperty("user.dir");
        File xsdFile = new File(path);
        if (xsdFile.isAbsolute()){
            if (!xsdFile.getParentFile().exists()){
                xsdFile.getParentFile().mkdirs();
            }
        }else{
            xsdFile = new File(local + File.separator + path);
        }
        if (xsdFile.exists()){
            // TODO 询问是否覆盖 暂时先删除
            xsdFile.delete();
        }
        xsdFile.createNewFile();

        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try {
            fos = new FileOutputStream(xsdFile);
            bw = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));
            bw.write(schema);
            bw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fos != null){
                fos.close();
            }
            if (bw != null){
                bw.close();
            }
        }
    };

}
